package com.tinytoon.hunghoaqua;

import java.util.concurrent.TimeUnit;
import android.graphics.Canvas;
import android.view.SurfaceHolder;

public class ViewThread extends Thread {
	private int FPS = 30;//Frame per second
    private Panel mPanel;
    private SurfaceHolder mHolder;
    private long mElapsed;
    private int mMode;
    public ViewThread(Panel panel) {
        mPanel = panel;
        mHolder = mPanel.getHolder();
    }
    
    
    public void setMode(int mode){
    	mMode = mode;
    }
    
    public int getMode(){
    	return mMode;
    }
    
    
    @Override
    public void run() {
        Canvas canvas = null;
        while (mPanel.mMode == Panel.MODE_RUNING) {
            long beginTimeMillis, timeTakenMillis, timeLeftMillis;
            beginTimeMillis = System.currentTimeMillis();  
        	
            canvas = mHolder.lockCanvas();
            if (canvas != null) {         	
            	//1.Get user input(touched point)
            	//2.DoLogic: create icon(x,y,speed)
				mPanel.doLogic(mElapsed);
				
				//3.Rendering
                mPanel.doDraw(mElapsed, canvas);
                mHolder.unlockCanvasAndPost(canvas);
            }
                        
         // get the time after processing and calculate the difference
            timeTakenMillis = System.currentTimeMillis() - beginTimeMillis;

            // check how long there is until we reach the desired refresh rate
            timeLeftMillis = (1000L / FPS) - timeTakenMillis;

            // set some kind of minimum to prevent spinning
            if (timeLeftMillis < 5) { 
                timeLeftMillis = 5; // Set a minimum
            }

            // sleep until the end of the current frame    
            try {
                TimeUnit.MILLISECONDS.sleep(timeLeftMillis);  
            } catch (InterruptedException ie) {
            }
            
        }
    }
}